//
//  MusicListViewController.m
//  MountEverestFM
//
//  Created by ChenNing on 15/10/30.
//  Copyright © 2015年 chenn. All rights reserved.
//

#import "MusicListViewController.h"
#import "MusicListTableViewCell.h"
#import "MusicHeadTableViewCell.h"
#import "Player.h"
#import "PlayerViewController.h"
#import "UIAlertTool.h"
#import "PlayerModel.h"
#import "MusicModel.h"

@interface MusicListViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSMutableDictionary *dataDictionary;
@property(nonatomic,strong)UITableView *mlTableView;

// 集数
@property(nonatomic,strong)UILabel *countLabel;
// 选集
@property(nonatomic,strong)UIImageView *selectImageView;
@property(nonatomic,strong)UIButton *selectButton;
// 排序
@property(nonatomic,strong)UIImageView *sortImageView;
@property(nonatomic,strong)UIButton *sortButton;

// 分享
@property (nonatomic, strong) UIView *panelView; // 分享面板
@property (nonatomic, strong) UIActivityIndicatorView *loadingView;//加载视图,转圈圈视图

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong) NSMutableDictionary *listDic;

@end

@implementation MusicListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self initMlListTableView];
    [self getDataWithUrl];
}

/**
 *  初始化mlTableView
 */
- (void)initMlListTableView
{
    self.mlTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,-FM_Screen_Pts_Height*150, FM_Screen_Width, FM_Screen_Height-48+FM_Screen_Pts_Height*150) style:UITableViewStyleGrouped];
    self.mlTableView.backgroundColor = UIColorFromRGB(0xe7e7e7);
    self.mlTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mlTableView.dataSource = self;
    self.mlTableView.delegate = self;
    [self.view addSubview:_mlTableView];
    
    [self.mlTableView registerClass:[MusicHeadTableViewCell class] forCellReuseIdentifier:@"headCell"];
    [self.mlTableView registerClass:[MusicListTableViewCell class] forCellReuseIdentifier:@"mlListCell"];
    
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        self.pageNum = _pageNum + 1;
        [self getDataWithUrl];
        NSLog(@"%ld", _pageNum);
        footer.automaticallyChangeAlpha = YES;
        [self.mlTableView.footer endRefreshing];
    }];
    self.mlTableView.footer = footer;
    
    //加载等待视图
    self.panelView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.panelView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.panelView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    
    self.loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    self.loadingView.frame = CGRectMake((self.view.frame.size.width - self.loadingView.frame.size.width) / 2, (self.view.frame.size.height - self.loadingView.frame.size.height) / 2, self.loadingView.frame.size.width, self.loadingView.frame.size.height);
    self.loadingView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    [self.panelView addSubview:self.loadingView];

}

// UITableViewDataSource 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.dataDictionary.count != 0) {
        return 2;
    } else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return [[[self.dataDictionary objectForKey:@"tracks"] objectForKey:@"list"] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return FM_Screen_Pts_Height*81+(FM_Screen_Width-FM_Screen_Pts_Width*40)/3+FM_Screen_Pts_Height*150+64;
    }else{
        return FM_Screen_Pts_Width*70+FM_Screen_Pts_Height*20;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        MusicHeadTableViewCell *headCell = [tableView dequeueReusableCellWithIdentifier:@"headCell"];
        headCell.selectionStyle = UITableViewCellSelectionStyleNone;
        headCell.headDictionary = [self.dataDictionary objectForKey:@"album"];
        [headCell.collectButton addTarget:self action:@selector(collectButton:) forControlEvents:UIControlEventTouchUpInside];
        [headCell.shareButton addTarget:self action:@selector(showShareActionSheet) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        return headCell;
    }
    else
    {
        MusicListTableViewCell *mlCell = [tableView dequeueReusableCellWithIdentifier:@"mlListCell"];
        mlCell.bodyDictionary = [[[self.dataDictionary objectForKey:@"tracks"] objectForKey:@"list"] objectAtIndex:indexPath.row];
        return mlCell;
    }
}

- (void)collectButton:(UIButton *)btn
{
    NSString *fmid = [[self.musicListDic objectForKey:@"albumId"] stringValue];
    if (fmid == nil) {
        // 单曲精选
        fmid = [[self.musicListDic objectForKey:@"id"] stringValue];
    }
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/20?device=iPhone",fmid];
    
    NSString *title = [[self.dataDictionary objectForKey:@"album"] objectForKey:@"title"];
    NSString *imageStr = [[self.dataDictionary objectForKey:@"album"] objectForKey:@"coverSmall"];
    CollectedModel *collectedModel = [CollectedModel collectModelWithAddress:url TitelStr:title Image:imageStr];
    DBHandler *db = [DBHandler shareInstance];
    [db openDB];
    [db insertCollect:collectedModel];
    [db closeDB];
    
    UIAlertTool *alert = [[UIAlertTool alloc]init];
    [alert showAlertView:self title:nil message:@"已收藏" cancelButtonTitle:@"OK" otherButtonTitle:nil confirm:^{
    } cancle:^{
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1)
    {
        NSString *fmid = [[self.musicListDic objectForKey:@"albumId"] stringValue];
        if (fmid == nil) {
            // 单曲精选
            fmid = [[self.musicListDic objectForKey:@"id"] stringValue];
        }
        NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/20?device=iPhone",fmid];
        
        Player *player = [Player shareInstance];
        if (player.playerModel != nil) {
            [player collectPreseve];
        }
        [self playingFM:indexPath.row requestUrl:url];
        self.tabBarController.selectedIndex = 2;
    }
}

// UITableViewDelegate 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
        return FM_Screen_Pts_Height*51;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FM_Screen_Width, FM_Screen_Pts_Height*51)];//创建一个视图（v_headerView）
        headerView.backgroundColor = UIColorFromRGB(0xe7e7e7);
//        headerView.backgroundColor = [UIColor whiteColor];
        // 集数
        NSDictionary *tracksDic = [self.dataDictionary objectForKey:@"tracks"];
        self.countLabel = [[UILabel alloc] initWithFrame:CGRectMake(FM_Screen_Pts_Width*10, FM_Screen_Pts_Height*10, FM_Screen_Height/3, FM_Screen_Pts_Height*30)];
        self.countLabel.text = [NSString stringWithFormat:@"共%d集", [[tracksDic objectForKey:@"list"] count]];
        self.countLabel.textColor = [UIColor grayColor];
        self.countLabel.font = [UIFont systemFontOfSize:15];
        [headerView addSubview:_countLabel];
        
        // 选集
//        self.selectImageView = [[UIImageView alloc] initWithFrame:CGRectMake(FM_Screen_Pts_Width*200, FM_Screen_Pts_Height*5,FM_Screen_Pts_Height*40, FM_Screen_Pts_Height*40)];
//        self.selectImageView.image = [UIImage imageNamed:@"toolbar_playinglist_n_p@2x.png"];
//        [headerView addSubview:_selectImageView];
//        
//        self.selectButton = [UIButton buttonWithType:UIButtonTypeSystem];
//        self.selectButton.frame = CGRectMake(FM_Screen_Pts_Width*234, FM_Screen_Pts_Height*10,FM_Screen_Pts_Width*50, FM_Screen_Pts_Height*30);
//        [self.selectButton setTitle:@"选集" forState:UIControlStateNormal];
//        self.selectButton.titleLabel.font = [UIFont systemFontOfSize:15];
//        // button文字局左
//        self.selectButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//        [self.selectButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//        [headerView addSubview:_selectButton];
//        
//        // 排序
//        self.sortButton = [UIButton buttonWithType:UIButtonTypeSystem];
//        self.sortButton.frame = CGRectMake(FM_Screen_Pts_Width*300, FM_Screen_Pts_Height*10, FM_Screen_Pts_Width*50, FM_Screen_Pts_Height*30);
//        self.sortButton.titleLabel.font = [UIFont systemFontOfSize:15];
//        [self.sortButton setTitle:@"排序" forState:UIControlStateNormal];
//        [self.sortButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//        
//        self.sortImageView = [[UIImageView alloc] initWithFrame:CGRectMake(FM_Screen_Pts_Width*350, FM_Screen_Pts_Height*18,FM_Screen_Pts_Height*15, FM_Screen_Pts_Height*15)];
//        self.sortImageView.image = [UIImage imageNamed:@"album_sortButton@2x.png"];
//        [headerView addSubview:_sortImageView];
//        
//        self.sortButton.titleLabel.textAlignment = NSTextAlignmentRight;
//        [headerView addSubview:_sortButton];
        
        return headerView;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = UIColorFromRGB(0xe7e7e7);
    return footerView;
}

/**
 *  网络请求
 */
- (void)getDataWithUrl
{
    self.dataDictionary = [NSMutableDictionary dictionary];
    NSString *fmid = [[self.musicListDic objectForKey:@"albumId"] stringValue];
    if (fmid == nil) {
        // 单曲精选
        fmid = [[self.musicListDic objectForKey:@"id"] stringValue];
    }
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?device=iPhone",fmid, self.pageNum];
   
    [NetWorkManager GET:url isCaChe:NO resultData:^(id responseObject) {
        self.dataDictionary = responseObject;
        [self.listDic setValuesForKeysWithDictionary:[_dataDictionary objectForKey:@"album"]];
        [self.mlTableView reloadData];
    } resultRrror:^(NSError *error) {
        NSLog(@"FM列表:error,%@",error);
    }];
}

// 播放音频
- (void)playingFM:(NSInteger)index requestUrl:(NSString *)requestUrl
{
    Player *play = [Player shareInstance];
    if (play.playerModel.musicArray.count != 0) {
        [play collectPreseve];
    }
    [play collectPreseve];
    //处理数据源
    PlayerModel *playerModel = [PlayerModel modelWithDic:[self.dataDictionary objectForKey:@"album"]];
    // 专辑序号
    playerModel.index = index;
    // 专辑请求地址
    playerModel.requstUrl = requestUrl;
    // 专辑列表
    playerModel.musicArray = [NSArray arrayWithArray:[MusicModel modelWithArr:[[self.dataDictionary objectForKey:@"tracks"] objectForKey:@"list"]]];

    // 数据源
    play.playerModel = playerModel;
    play.history = NO;
    
    // 播放
    [play playFromNet];
}

- (void)viewWillDisappear:(BOOL)animated
{
    // 加线
    self.navigationController.navigationBar.layer.masksToBounds = NO;
    // 导航栏非透明
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsCompact];
}

- (void)viewWillAppear:(BOOL)animated
{
    // 去线
    self.navigationController.navigationBar.layer.masksToBounds = YES;
    // 导航栏透明
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bigShadow.png"] forBarMetrics:UIBarMetricsCompact];
}

/**
 *  显示加载动画
 *
 *  @param flag YES 显示，NO 不显示
 */
- (void)showLoadingView:(BOOL)flag
{
    if (flag)
    {
        [self.view addSubview:self.panelView];
        [self.loadingView startAnimating];
    }
    else
    {
        [self.panelView removeFromSuperview];
    }
}
/**
 *  显示分享菜单
 *
 *  @param view 容器视图
 */
- (void)showShareActionSheet
{
#warning 2 设置分享参数
    /**
     *  @param text     文本
     *  @param images   图片集合,传入参数可以为单张图片信息，也可以为一个NSArray，数组元素可以为UIImage、NSString（图片路径）、NSURL（图片路径）、SSDKImage，
     *                  如: @"http://mob.com/Assets/images/logo.png?v=20150320" 或 @[@"http://mob.com/Assets/images/logo.png?v=20150320"]
     *  @param url      网页路径/应用路径
     *  @param title    标题
     *  @param type     分享类型
     */
    MusicListViewController *theController = self;
    
    //1、创建分享参数（必要）
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    /*
     四种发送图片的方式
     NSString *uriStr1 = @"http://www.baidu.com/img/bd_logo1.png";
     NSArray *imageArr2 = @[@"http://www.baidu.com/img/bd_logo1.png",@"http://t3.qlogo.cn/mbloghead/5a40b92d58ee28b944d2/100"];
     NSArray *imageArr3 = @[[NSURL URLWithString:@"http://www.baidu.com/img/bd_logo1.png"],[NSURL URLWithString:@"http://t3.qlogo.cn/mbloghead/5a40b92d58ee28b944d2/100"]];
     NSArray *imageArr4 = @[[UIImage imageNamed:@"108*108.png"],[UIImage imageNamed:@"28*28.PNG"]];
     */
    
    [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                     images:nil
                                        url:nil
                                      title:@"珠穆朗玛FM"
                                       type:SSDKContentTypeAuto];
    
#warning 3 显示分享菜单,分享
    /**
     *  @param view                     要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图
     *  @param items                    菜单项，如果传入nil，则显示已集成的平台列表
     *  @param shareParams              分享内容参数
     *  @param shareStateChangedHandler 分享状态变更事件
     *
     *  @return 分享菜单控制器
     */
    [ShareSDK showShareActionSheet:nil
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   switch (state) {
                           
                       case SSDKResponseStateBegin:
                       {
                           [theController showLoadingView:YES];
                           break;
                       }
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           if (platformType == SSDKPlatformTypeSMS && [error code] == 201)
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:@"失败原因可能是：1、短信应用没有设置帐号；2、设备不支持短信应用；3、短信应用在iOS 7以上才能发送带附件的短信。"
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           else if(platformType == SSDKPlatformTypeMail && [error code] == 201)
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:@"失败原因可能是：1、邮件应用没有设置帐号；2、设备不支持邮件应用；"
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           else
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           break;
                       }
                       default:
                           break;
                   }
                   
                   if (state != SSDKResponseStateBegin)
                   {
                       [theController showLoadingView:NO];
                   }
                   
               }];
}

@end
